package com.atguigu.lease.admin.controller.apartment;

import com.atguigu.lease.admin.service.FeeKeyService;
import com.atguigu.lease.admin.service.FeeValueService;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.bean.FeeKey;
import com.atguigu.lease.model.bean.FeeValue;
import com.atguigu.lease.model.vo.FeeKeyVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "杂费管理模块")
@RestController
@RequestMapping("/admin/fee")
public class FeeKeyController {
    @Autowired
    private FeeKeyService feeKeyService;
    @Autowired
    private FeeValueService feeValueService;
    // fee_key:杂费名称表  fee_value：杂费值表
    @Operation(summary = "1、查询所有杂费名称和值列表")
    @GetMapping("/list")
    public Result<List<FeeKeyVo>> list(){
        return Result.ok(feeKeyService.listFeeKeyVos());
    }
    ///admin/fee/key/saveOrUpdate
    @Operation(summary = "2、新增或更新杂费名称")
    @PostMapping("/key/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody FeeKey feeKey){
        return Result.ok(feeKeyService.saveOrUpdate(feeKey));
    }
    ///admin/fee/value/saveOrUpdate
    @Operation(summary = "3、新增或更新杂费值")
    @PostMapping("/value/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody FeeValue feeValue){
        return Result.ok(feeValueService.saveOrUpdate(feeValue));
    }
    ///admin/fee/value/deleteById?id=23
    @Operation(summary = "4、根据id删除FeeValue")
    @DeleteMapping("/value/deleteById")
    public Result deleteValueById(@RequestParam Long id){
        return Result.ok(feeValueService.removeById(id));
    }
    ///admin/fee/key/deleteById?feeKeyId=9
    @Operation(summary = "5、根据feeKeyId删除FeeKey")
    @DeleteMapping("/key/deleteById")
    public Result deleteKeyById(@RequestParam Long feeKeyId){
        //判断：如果feeKeyId 没有可用的FeeValue才可以删除
        long count = feeValueService.count(Wrappers.lambdaQuery(FeeValue.class)
                .eq(FeeValue::getFeeKeyId, feeKeyId));
        if(count>0){
            return Result.error(ResultCodeEnum.DELETE_ERROR);
        }
        return Result.ok(feeKeyService.removeById(feeKeyId));
    }
}
